<template>
  <div class="login-container">
    <div class=" max-w-6xl w-full h-screen m-auto flex items-center justify-end px-8">

      <div class="w-96 shadow rounded p-12 bg-back relative">
        <div class="absolute top-0 left-4">
          <lang class="mr-3" @refreshComponent="refreshComponent" />
        </div>
        <div v-if="route?.query.official" :class="['modeChange', mode === 1 ? 'modeAdmin' : '']" @click="modeChange">
          <img v-if="mode === 0" class="modeImg" src="@/assets/login-code.png" alt="">
          <img v-else-if="mode === 1" class="modeImg" src="@/assets/login-admin.png" alt="">
        </div>
        <p class="text-center mb-8 text-2xl text-red-700">
          <span v-if="mode === 0">{{ $t('public.logn') }}</span>
          <span v-else-if="mode === 1">{{ $t('public.scanCode') }}</span>
        </p>
        <template v-if="mode === 0 && scan.status">
          <el-form ref="loginFormRef" :model="loginForm" label-position="left" size="large">

            <el-form-item prop="account"
              :rules="[{ required: true, message: $t('message.pleaseEnterAccount'), trigger: 'blur' }]">
              <el-input :prefix-icon="User" v-model="loginForm.account" :placeholder="$t('message.pleaseEnterAccount')"
                type="text" auto-complete="on" />
            </el-form-item>

            <el-form-item prop="password"
              :rules="[{ required: true, message: $t('message.enterUserPass'), trigger: 'blur' }]">
              <el-input :prefix-icon="Lock" v-model="loginForm.password" :placeholder="$t('message.enterUserPass')"
                :show-password="true" type="password" />
            </el-form-item>

            <el-form-item prop="code"
              :rules="[{ required: true, message: $t('message.pleaseEnterVerifi'), trigger: 'blur' }]">
              <div class="w-full relative">
                <el-input v-model="loginForm.code" :placeholder="$t('message.pleaseEnterVerifi')" type="text"
                  maxlength="5" />
                <div class="absolute right-0 top-0 h-full bg-red-600 w-1/2" @click="getCaptchaImg()">
                  <img :src="captchaImg.url" alt="" class="h-full w-full truncate">
                  <!-- <img :src="captchaImg.url" alt="" class="h-full w-full truncate"> -->
                </div>
              </div>
            </el-form-item>

          </el-form>
          <el-form>
            <el-button :loading="loading" type="danger" size="large" class="loginbutton" @click.prevent="handleLogin()"
              @keydown.enter="keyDown()">
              {{ $t('public.sign') }}
            </el-button>
          </el-form>
        </template>
        <template v-else-if="mode === 1 && scan.status">
          <div class="codeWrap relative">
            <div id="imgContainer"
              :class="scan.status == 2 || scan.status == 4 ? 'errqrCode relative successCode' : 'errqrCode  relative'"
              v-if="scan.login_url && scan.status">
            </div>
            <div id="imgContainer" v-else class="errqrCode relative failCode">
            </div>
            <div class="absolute top-14 left-24" v-if="scan.status == 2">
              <img class="w-24" src="@/assets/ok.png" alt="">
              <p class="mb-2">{{ $t('public.Scanned') }}</p>
            </div>
            <div class="absolute top-14 left-24" v-if="scan.status == 4">
              <p class="">{{ $t('public.QRexpired') }}</p>
              <p class="text-[#409Eff] cursor-pointer scans">{{ $t('public.refresh') }}</p>
            </div>
            <p class="mt-2" v-if="scan.status == 2">{{ $t('message.pleaseAccount') }}</p>
            <div class="mt-2" v-if="scan.status == 1">{{ $t('message.pleaseWeChat') }}</div>
            <p class="text-[#409Eff] cursor-pointer scans" @click="findScans">{{
              $t('public.again') }}</p>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t, locale } = useI18n()
import { FormInstance } from 'element-plus';
import useUserStore from '@/store/user';
import { useRoute, useRouter } from 'vue-router';
import { getCaptcha } from '@/api/login';
import { User, Lock } from '@element-plus/icons-vue';
import { nextTick, onMounted } from 'vue'
import { getWxLoginUrl, checkWxLoginStatus } from '@/api/login'
import QRCode from 'qrcodejs2-fix';
let mode = ref(0) // 0-账密登录 1-扫码登录
const userStore = useUserStore()
const router = useRouter()
let captchaImg = reactive({
  url: ''
})
const loginForm = reactive({
  account: '', // dkm
  password: '', // 123456
  code: '',
  uniqid: '',
})
let scan = ref({
  id: 0, // 登录日志ID 
  timer: null, // 定时器
  status: 1,
  code: null,
  login_url: '', // 二维码
  qrCode: ''
})
onMounted(() => {
  if (route?.query.official) {
    localStorage.setItem('official', route?.query.official)
  }
  if (!route?.query) {
    localStorage.removeItem('official')
  }
})
let componentKey = ref(0)
const loading = ref(false)
// redirect path
const route = useRoute()
const redirect = route.query.redirect ? route.query.redirect : ''
const loginFormRef = ref<FormInstance>()
const emits = defineEmits(['refreshComponent'])
// 登录模式切换
let modeChange = () => {
  if (mode.value === 0) {
    mode.value = 1
  } else {
    mode.value = 0
  }
  if (scan.value.timer) {
    scan.value.status = 1
    clearInterval(scan.value.timer)
    scan.value.timer = null
  }
  getQrcode()
}
let findScans = () => {
  scan.value.status = 1
  if (scan.value.timer) {
    clearInterval(scan.value.timer)
    scan.value.timer = null
  }
  getQrcode()
}
// 获取登录二维码
let getQrcode = () => {
  if (mode.value === 1) {
    getWxLoginUrl({ official: route?.query.official }).then(res => {
      scan.value.id = res.data.id
      scan.value.login_url = res.data.login_url
      listenQrcode()
      nextTick(() => {
        generateCode()
      })
    })
  }
}
const generateCode = () => {
  document.getElementById("imgContainer").innerHTML = "";
  new QRCode(document.getElementById("imgContainer"), {
    text: scan.value.login_url
  });
};

// 监听扫码登录
let listenQrcode = () => {
  if (scan.value.timer) {
    clearInterval(scan.value.timer)
    scan.value.timer = null
  }
  scan.value.timer = setInterval(() => {
    checkWxLoginStatus({ id: scan.value.id }).then(res => {
      scan.value.status = res.data.status
      if (res.data.status === 3) {
        clearInterval(scan.value.timer)
        sessionStorage.setItem('clean', true)
        scan.value.timer = null
        userStore.token = res.data.login_token
        location.reload()
      }
    })
  }, 2000)
}

const refreshComponent = () => {
  //切换国际化语言
  if (locale.value === 'en') {
    locale.value = 'en'
  }
  else if (locale.value === 'zh') {
    locale.value = 'zh'
  }
  else if (locale.value === 'tw') {
    locale.value = 'tw'
  }
  componentKey.value++;
}
const keyDown = (e) => {
  if (e.keyCode == 13) {
    handleLogin()
  }
}

window.addEventListener('keydown', keyDown)

const handleLogin = () => {
  if (!loginFormRef.value) return
  loginFormRef.value.validate((valid) => {
    if (valid) {
      console.log('submit !')
      loading.value = true
      userStore.login(loginForm).then((res) => {
        loading.value = false
        if (res.state == 200) {
          window.removeEventListener('keydown', keyDown, false)
          router.push({ path: redirect.toString() || '/' })
          return
        }
        ElMessage({
          message: res.msg,
          type: 'error'
        })
        loginForm.code = ''
        getCaptchaImg()

      }).catch((err) => {
        loading.value = false
        loginForm.code = ''
        getCaptchaImg()
        console.log(err)
      })
    } else {
      return false
    }
  })
}

const getCaptchaImg = () => {
  getCaptcha().then(res => {
    if (res.state == 200) {
      loginForm.uniqid = res.data.uniqid
      captchaImg.url = res.data.content
    }
  })
}
getCaptchaImg()
</script>

<style lang="scss">
.login-container {
  background-image: url('@/assets/login-bg.webp');
  background-size: cover;
  background-position: center;

  .scans {
    color: #409Eff !important;
  }

  .failCode {
    line-height: 200px;
    background-color: #c0bcbcd9;
    opacity: 0.4;
  }

  .errqrCode {
    min-height: 200px;
    max-width: 200px;

  }

  .successCode::after {
    position: absolute;
    background-color: #ffffffd9;
    content: '';
    right: 0;
    left: 0;
    top: 0;
    bottom: 0;
  }

  .modeChange {
    position: absolute;
    z-index: 9;
    top: 0;
    right: 0;
    cursor: pointer;
    width: 80px;
    height: 80px;
    padding: 10px;

    .modeImg {
      width: 100%;
      height: 100%;
    }

    &:before {
      content: "";
      display: block;
      border-style: solid;
      border-width: 40px;
      border-color: transparent transparent #eee #eee;
      position: absolute;
      top: 0;
      right: 0;
      box-shadow: -3px 3px 20px 0px rgba(0, 0, 0, 0.2);
      transition: all .3s;
    }

    &:hover {
      &:before {
        border-width: 45px;
      }
    }
  }

  .modeAdmin {
    padding: 10px 10px 30px 30px;
  }

  .codeWrap {
    text-align: center;
    padding-top: 10px;

    #imgContainer {
      min-height: 200px;
      max-width: 200px;
      margin: auto;
    }

    p {
      // margin-top: 40px;
      font-size: 16px;
      color: #1a1a1a;
    }
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    height: 48px;

    input {
      background: transparent;
      border: 0px;
      border-radius: 0px;
      padding: 0 10px;
      color: #545454;
    }

    .el-input__wrapper {
      padding: 0 15px;
    }
  }
}

.loginbutton {
  width: 100%;
  margin-bottom: 30px;
  background: #d7000f;
  color: #fafafa;
  font-size: 16px;
}
</style>
